package com.strelitzia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import com.strelitzia.dao.UserDao;
import com.strelitzia.entity.FriendItem;
import com.strelitzia.entity.FriendsEntity;
import com.strelitzia.entity.NotificationEntity;
import com.strelitzia.entity.UserEntity;
import com.strelitzia.exception.StrelitziaException;
import com.strelitzia.filter.CorsFilter;
import com.strelitzia.service.FriendsService;
import com.strelitzia.service.NotificationService;
import com.strelitzia.service.UserService;
import com.strelitzia.utils.FileUtil;
import com.strelitzia.utils.TimeUtil;
import com.strelitzia.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;


/**
 * @create 2023/12/14 15:29
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private FriendsService friendsService;

    @Autowired
    private NotificationService notificationService;

    @Override
    public String regis(RegForm regForm) {
        if (this.count(new QueryWrapper<UserEntity>().eq("username", regForm.getUsername())) > 0) {
            return "用户名已注册";
        }

        if (this.count(new QueryWrapper<UserEntity>().eq("email", regForm.getEmail())) > 0) {
            return "邮箱已注册";
        }

        try {
            String code = redisTemplate.opsForValue().get(regForm.getEmail());

            if (StringUtils.isNullOrEmpty(code) || !code.trim().equals(regForm.getCode().trim())) {
                return "验证码错误";
            }
        } catch (Exception e) {
            return "验证码错误";
        }
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(regForm, userEntity);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(regForm.getPassword());
        userEntity.setPassword(password);
        userEntity.setNickname("用户" + new Random().nextInt(99999 - 10000 + 1 + 10000));
        userEntity.setAvatar("user.png");
        userEntity.setGender("");
        userEntity.setSignature("");
        userEntity.setStatus(0);
        userEntity.setRegisDate(new Date(new java.util.Date().getTime()));
        this.save(userEntity);
        return "";
    }

    @Override
    public UserEntity login(LoginForm loginForm) {
        UserEntity userEntity = this.getOne(new QueryWrapper<UserEntity>()
                .eq("username", loginForm.getUsername())
                .or(w -> w.eq("email", loginForm.getUsername())));
        if (userEntity != null) {
            BCryptPasswordEncoder bpe = new BCryptPasswordEncoder();
            if (bpe.matches(loginForm.getPassword(), userEntity.getPassword())) {
                if (userEntity.getStatus() != 0) {
                    userEntity.setStatus(1);
                    this.setStatus(1);
                }
                return userEntity;
            }
        }
        return null;
    }

    @Override
    public UserEntity updateUser(UpdateUserForm form) throws StrelitziaException {
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(form, userEntity);
        userEntity.setId(CorsFilter.loginUserId.get());
        if (form.getAvatarFile() != null && !"".equals(form.getAvatarFile().getOriginalFilename())) {
            String src = FileUtil.fileUp(form.getAvatarFile());
            if (!src.equals("")) {
                userEntity.setAvatar(src);
                System.out.println(src);
            } else {
                throw new StrelitziaException("上传头像失败");
            }
        }
        this.updateById(userEntity);
        return this.getById(userEntity.getId());
    }

    @Override
    public UserItem get(Integer id) {
        UserEntity byId = this.getById(id);
        UserItem userItem = new UserItem();
        BeanUtils.copyProperties(byId, userItem);
        FriendsEntity one = friendsService.getOne(new QueryWrapper<FriendsEntity>().eq("uid", CorsFilter.loginUserId.get()).eq("friend_id", id));
        if (one != null) {
            userItem.setIsFriend(true);
            userItem.setRemark(one.getRemark());
        } else {
            userItem.setRemark("");
            userItem.setIsFriend(false);
        }
        userItem.setAvatar("/api/res/" + byId.getAvatar());
        NotificationEntity notificationEntity = notificationService.getFriend(CorsFilter.loginUserId.get(), id);
        System.out.println(notificationEntity);
        if (notificationEntity != null) {
            if (TimeUtil.TimestampMinus(notificationEntity.getTime()) > 0) {
                notificationEntity.setId(null);
                notificationEntity.setTime(new Timestamp(new java.util.Date().getTime()));
                notificationService.save(notificationEntity);
            }
        } else {
            notificationEntity = new NotificationEntity();
            notificationEntity.setType(2);
            notificationEntity.setNotifier(CorsFilter.loginUserId.get());
            notificationEntity.setMessage("访问了你的主页");
            notificationEntity.setReceiver(id);
            notificationEntity.setTime(new Timestamp(new java.util.Date().getTime()));
            notificationService.save(notificationEntity);
        }


        return userItem;
    }

    @Override
    public Integer getKeyword(String keyword) {
        UserEntity one = this.getOne(new QueryWrapper<UserEntity>().eq("username", keyword).or().eq("email", keyword));
        if (one != null) {
            return one.getId();
        } else {
            return 0;
        }

    }

    @Override
    public Integer setStatus(Integer status) {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(CorsFilter.loginUserId.get());
        userEntity.setStatus(status);
        this.updateById(userEntity);
        return userEntity.getStatus();
    }

    @Override
    public void offline(Integer userId) {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(userId);
        userEntity.setStatus(2);
        this.updateById(userEntity);
    }


}
